<template>
  <div class="register">
    <div class="register-container">
      <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form">
        <h3 class="title">{{ title }}</h3>
        <!-- 滚动区域 -->
        <div class="form-scroll-container">

          <!-- 第一列 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用　　户" prop="userName" style="display: flex; align-items: center;">
                <el-input v-model="registerForm.userName" type="text" auto-complete="off" placeholder="登录账户" style="width: 250px;">
                  <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
                </el-input>
              </el-form-item>

              <!-- 用户性别 -->
              <el-form-item label="性　　别" prop="sex" style="display: flex; align-items: center;">
                <el-select v-model="registerForm.sex" placeholder="性别" style="width: 250px;">
                  <el-option label="男" value="0"></el-option>
                  <el-option label="女" value="1"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="身份证号" prop="idcard" style="display: flex; align-items: center;">
                <el-input v-model="registerForm.idcard" placeholder="身份证号码" style="width: 250px;"></el-input>
              </el-form-item>

              <el-form-item label="出生日期" prop="birthday" style="display: flex; align-items: center;">
                <el-date-picker v-model="registerForm.birthday" type="date" placeholder="出生日期"
                                style="width: 250px;" value-format="yyyy-MM-dd"/>
              </el-form-item>

              <el-form-item label="文化程度" prop="culture" style="display: flex; align-items: center;">
                <el-select v-model="registerForm.culture" placeholder="文化程度" style="width: 250px;">
                  <el-option label="小学" value="小学"></el-option>
                  <el-option label="初中" value="初中"></el-option>
                  <el-option label="高中" value="高中"></el-option>
                  <el-option label="大专" value="大专"></el-option>
                  <el-option label="本科" value="本科"></el-option>
                  <el-option label="硕士" value="硕士"></el-option>
                  <el-option label="博士" value="博士"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="政治面貌" prop="political" style="display: flex; align-items: center;">
                <el-select v-model="registerForm.political" placeholder="政治面貌" style="width: 250px;">
                  <el-option label="党员" value="党员"></el-option>
                  <el-option label="群众" value="群众"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="籍　　贯" prop="nativeplace" style="display: flex; align-items: center;">
                <el-input v-model="registerForm.nativeplace" placeholder="籍贯" style="width: 250px;"></el-input>
              </el-form-item>

              <el-form-item label="工作时间" prop="workDate" style="display: flex; align-items: center;">
                <el-date-picker v-model="registerForm.workDate" type="date" placeholder="工作时间"
                                style="width: 250px;" />
              </el-form-item>
            </el-col>
            <!-- 第二列 -->
            <el-col :span="12">
              <el-form-item label="姓　　名" prop="nickName" style="display: flex; align-items: center;">
                <el-input v-model="registerForm.nickName" type="text" auto-complete="off" placeholder="姓名" style="width: 250px;">
                  <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
                </el-input>
              </el-form-item>
              <!-- 单位编号 -->
              <el-form-item label="单位编号" prop="deptId" style="display: flex; align-items: center;">
                <el-input v-model.number="registerForm.deptId" placeholder="向单位人力部门询问后填写" :controls="false" style="width: 250px;"/>
              </el-form-item>

              <el-form-item label="军　　衔" prop="jxClass" style="display: flex; align-items: center;">
                <el-select v-model="registerForm.jxClass" placeholder="请选择退伍时军衔" style="width: 250px;">
                  <el-option label="义务兵" value="义务兵"></el-option>
                  <el-option label="下士" value="下士"></el-option>
                  <el-option label="中士" value="中士"></el-option>
                  <el-option label="二级上士" value="二级上士"></el-option>
                  <el-option label="一级上士" value="一级上士"></el-option>
                  <el-option label="三级军士长" value="三级军士长"></el-option>
                  <el-option label="二级军士长" value="二级军士长"></el-option>
                  <el-option label="一级军士长" value="一级军士长"></el-option>

                </el-select>
              </el-form-item>

              <el-form-item label="职业技能" prop="major" style="display: flex; align-items: center;">
                <el-input v-model="registerForm.major" placeholder="职业技能专业" style="width: 250px;"></el-input>
              </el-form-item>

              <el-form-item label="技能等级" prop="level" style="display: flex; align-items: center;">
                <el-input v-model="registerForm.level" placeholder="技能等级" style="width: 250px;"></el-input>
              </el-form-item>

              <el-form-item label="奖惩情况" prop="rewards" style="display: flex; align-items: center;">
                <RewardMultiSelect v-model="registerForm.rewards" placeholder="奖惩情况" style="width: 250px;"></RewardMultiSelect>
              </el-form-item>

              <!-- 手机号码 -->
              <el-form-item label="手机号码" prop="phonenumber" style="display: flex; align-items: center;">
                <el-input v-model="registerForm.phonenumber" placeholder="手机号码" style="width: 250px;"></el-input>
              </el-form-item>

              <el-form-item label="家庭住址" prop="addr" style="display: flex; align-items: center;">
                <el-input v-model="registerForm.addr" placeholder="家庭住址" style="width: 250px;"></el-input>
              </el-form-item>


            </el-col>
          </el-row>
        </div>



        <el-form-item prop="password" style="display: inline-block; width: 48%;">
          <el-input
            v-model="registerForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleRegister"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword" style="display: inline-block; width: 48%; margin-left: 2%;">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            auto-complete="off"
            placeholder="确认密码"
            @keyup.enter.native="handleRegister"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>


        <!-- 验证码和提交按钮 -->
        <el-form-item prop="code" v-if="captchaEnabled">
          <div class="captcha-container">
            <el-input v-model="registerForm.code" placeholder="验证码"
                      @keyup.enter.native="handleRegister">
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
            </el-input>
            <div class="register-code" @click="getCode">
              <img :src="codeUrl" class="register-code-img"/>
            </div>
          </div>
        </el-form-item>

        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%;"
            @click.native.prevent="handleRegister"
          >
            <span v-if="!loading">注 册</span>
            <span v-else>注 册 中...</span>
          </el-button>
          <div style="float: right;">
            <router-link class="link-type" :to="'/login'">使用已有账户登录</router-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!--  底部  -->
    <div class="el-register-footer">
      <span>Copyright © 2018-2025 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import {getCodeImg, register} from "@/api/login"
import {addUser} from "@/api/system/user";
import RewardMultiSelect from "@/components/RewardMultiSelect.vue";

function isValidDate(idcard) {
  const year = parseInt(idcard.substr(6, 4), 10);
  const month = parseInt(idcard.substr(10, 2), 10);
  const day = parseInt(idcard.substr(12, 2), 10);
  const date = new Date(year, month - 1, day);
  return (
    date.getFullYear() === year &&
    date.getMonth() + 1 === month &&
    date.getDate() === day
  );
}

function validateIdCardCheckDigit(idcard) {
  const Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  const Ai = ['1','0','X','9','8','7','6','5','4','3','2'];
  let sigma = 0;
  for (let i = 0; i < 17; i++) {
    sigma += parseInt(idcard[i], 10) * Wi[i];
  }
  const checkCode = Ai[sigma % 11];
  return idcard[17].toString().toUpperCase() === checkCode;
}


export default {
  components: {
    RewardMultiSelect
  },
  name: "Register",
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("两次输入的密码不一致"))
      } else {
        callback()
      }
    }
    return {
      title: process.env.VUE_APP_TITLE,
      codeUrl: "",
      registerForm: {
        userName: "",
        password: "",
        status: "0",
        delFlag: "0",
        confirmPassword: "",
        code: "",
        uuid: "",
        idcard: "",
        birthday: null,
        culture: "",
        political: "",
        nativeplace: "",
        workDate: null,
        jxClass: "",
        major: "",
        level: "",
        rewards: '',
        addr: "",
        deptId: null,       // 新增：部门编号
        phonenumber: "",    // 新增：手机号码
        sex: "",             // 新增：性别
        nickName: "",       // 新增：用户昵称
        postIds: [4],        // 新增：岗位值固定为4
        roleIds: [2]     ,    // 新增：角色

        email: null,
        remark: null,
      },

      registerRules: {
        userName: [
          {required: true, trigger: "blur", message: "请输入您的账号"},
          {min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        nickName: [
          {required: true, trigger: "blur", message: "请输入您的账号"},
          {min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        deptId: [
          { required: true, message: "请输入部门编号", trigger: "blur" },
          { type: "number", min: 1, message: "部门编号必须大于0", trigger: "blur" }
        ],
        phonenumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { pattern: /^1[3-9][0-9]\d{8}$/, message: "手机号码格式不正确", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "请选择性别", trigger: "change" }
        ],
        idcard: [
          { required: true, message: "请输入身份证号码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!/^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dxX]$/.test(value)) {
                callback(new Error("身份证号码格式不正确"));
              } else if (!isValidDate(value)) {
                callback(new Error("身份证号码中的出生日期不合法"));
              } else if (!validateIdCardCheckDigit(value)) {
                callback(new Error("身份证号码最后一位校验码错误"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],

        birthday: [
          {required: true, message: "请选择出生日期", trigger: "change"}
        ],
        culture: [
          {required: true, message: "请选择文化程度", trigger: "change"}
        ],
        political: [
          {required: true, message: "请选择政治面貌", trigger: "change"}
        ],
        nativeplace: [
          {required: true, message: "请输入籍贯", trigger: "blur"}
        ],
        workDate: [
          {required: true, message: "请选择工作时间", trigger: "change"}
        ],
        jxClass: [
          {required: true, message: "请输入JX分类", trigger: "blur"}
        ],
        major: [
          {required: true, message: "请输入职业技能专业", trigger: "blur"}
        ],
        level: [
          {required: true, message: "请输入技能等级", trigger: "blur"}
        ],
        rewards: [
          {required: true, message: "请输入奖惩情况", trigger: "blur"}
        ],
        addr: [
          {required: true, message: "请输入家庭住址", trigger: "blur"}
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"},
          {min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur"},
          {pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur"}
        ],
        confirmPassword: [
          {required: true, trigger: "blur", message: "请再次输入您的密码"},
          {required: true, validator: equalToPassword, trigger: "blur"}
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}]
      },
      loading: false,
      captchaEnabled: true,
      rewardData: '{"一等奖":2,"二等奖":1}'
    }
  },
  created() {
    this.getCode()
  },
  watch: {
    'registerForm.idcard'(newVal) {
      if (newVal && (newVal.length === 15 || newVal.length === 18)) {
        const birthday = this.extractBirthdayFromIdCard(newVal);
        if (birthday) {
          this.registerForm.birthday = birthday;
        }
      }
    }
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img
          this.registerForm.uuid = res.uuid
        }
      })
    },
    // 提取出生日期
    extractBirthdayFromIdCard(idcard) {
      let year, month, day;

      if (idcard.length === 15) {
        const birthYear = idcard.substring(6, 8);
        const birthMonth = idcard.substring(8, 10);
        const birthDay = idcard.substring(10, 12);
        year = '19' + birthYear;
        month = birthMonth;
        day = birthDay;
      } else if (idcard.length === 18) {
        year = idcard.substring(6, 10);
        month = idcard.substring(10, 12);
        day = idcard.substring(12, 14);
      } else {
        return null;
      }

      // 简单校验日期是否合法
      const date = new Date(year, month - 1, day);
      if (
        date.getFullYear() === parseInt(year) &&
        date.getMonth() + 1 === parseInt(month) &&
        date.getDate() === parseInt(day)
      ) {
        return `${year}-${month}-${day}`;
      }

      return null;
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          // 格式化 birthday 为 yyyy-MM-dd
          // if (this.registerForm.birthday) {
          //   const date = new Date(this.registerForm.birthday);
          //   this.registerForm.birthday = date.toISOString().split('T')[0]; // 转换为 "YYYY-MM-DD"
          // }
          console.log(this.registerForm.birthday);

          this.loading = true
          register(this.registerForm).then(res => {
            const userName = this.registerForm.userName
            this.$alert("<font color='red'>恭喜你，您的账号 " + userName + " 注册成功！</font>", '系统提示', {
              dangerouslyUseHTMLString: true,
              type: 'success'
            }).then(() => {
              this.$router.push("/login")
            }).catch(() => {
            })
          }).catch(() => {
            this.loading = false
            if (this.captchaEnabled) {
              this.getCode()
            }
          })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("../assets/images/background.jpg");
  background-size: cover;
}

.register-form {
  border-radius: 6px;
  background: #ffffff;
  width: 800px; /* 调整宽度 */
  padding: 25px 25px 15px 25px;

  .form-scroll-container {
    max-height: 400px; // 控制最大高度
    overflow-y: auto; // 启用垂直滚动条
    padding-right: 10px;
  }

  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.register-code {
  cursor: pointer;
  height: 38px;
  display: flex;
  align-items: center;
}

.register-code-img {
  height: 100%;
  border-radius: 4px;
}


</style>
